package com.dacool.fragment;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.dialog.BasePickerDialog.PickerDialogDelegate;
import com.dacool.dialog.PickCityDialog;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.RegRequest;
import com.dacool.model.DCUser;
import com.dacool.model.Region;
import com.dacool.util.ViewUtils;

public class RegisterFragment extends BaseFragment implements OnClickListener {

	private ImageView checkImage;
	boolean checked = false;

	private EditText accountInput;
	private EditText nameInput;
	private EditText emailInput;
	private EditText passwordInput;
	private EditText confirmPasswordInput;
	private EditText recommenderInput;
	private View regionSelect;
	private TextView regionLabel;
	private TextView statementLink;

	private ArrayList<Region> regions;

	private Button registerButton;

	private int selectedRegion = 0;

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_register;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		checkImage = ViewUtils.findViewById(view, R.id.checkbox);
		checkImage.setOnClickListener(this);
		regions = Config.sharedConfig().getRegionsByParentID(0);
		accountInput = ViewUtils.findViewById(view, R.id.accountinput);
		nameInput = ViewUtils.findViewById(view, R.id.nameinput);
		emailInput = ViewUtils.findViewById(view, R.id.emailinput);
		passwordInput = ViewUtils.findViewById(view, R.id.passwordinput);
		confirmPasswordInput = ViewUtils.findViewById(view,
				R.id.confirmpasswordinput);
		recommenderInput = ViewUtils.findViewById(view, R.id.recommenderinput);
		regionSelect = ViewUtils.findViewById(view, R.id.regionSelect);
		regionSelect.setOnClickListener(this);
		regionLabel = ViewUtils.findViewById(view, R.id.regionLabel);

		statementLink = ViewUtils.findViewById(view, R.id.statementlink);
		statementLink.setOnClickListener(this);

		registerButton = ViewUtils.findViewById(view, R.id.registerbutton);
		registerButton.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (checkImage == v) {
			checked = !checked;
			if (checked)
				checkImage.setImageResource(R.drawable.icon_check);
			else
				checkImage.setImageDrawable(null);
		} else if (regionSelect == v) {

			new PickCityDialog(getActivity()).setRegions(regions)
					.setSelectedIndex(selectedRegion)
					.setDelegate(new PickerDialogDelegate() {

						@Override
						public void selectedItemAtIndex(int index) {
							// TODO Auto-generated method stub
							selectedRegion = index;
							regionLabel.setText(String.format("所在地区 : %s",
									regions.get(selectedRegion).name));
						}

						@Override
						public void didCancel() {
							// TODO Auto-generated method stub

						}
					}).show();
		} else if (statementLink == v) {
			WebViewFragment fragment = new WebViewFragment();
			fragment.setTitle("服务条款");
			fragment.setUrl("http://app.dacool.com/dcmapp/api/proto.html");
			getContainerActivity().addFragment(fragment);
		} else if (registerButton == v) {
			if (validate())
				performRegister();
		} else
			super.onClick(v);
	}

	private boolean validate() {
		boolean valid = true;
		valid &= accountInput.getText().length() > 0;
		if (!valid) {
			Toast.makeText(getActivity(), "请输入账号", Toast.LENGTH_LONG).show();
			return valid;
		}
		Pattern p = Pattern.compile("^1\\d{10}$");
		Matcher matcher = p.matcher(accountInput.getText().toString());
		if (!matcher.matches()) {
			Toast.makeText(getActivity(), "请输入11位手机号!", Toast.LENGTH_LONG)
					.show();
			return false;
		}
		valid &= nameInput.getText().length() > 0;
		if (!valid) {
			Toast.makeText(getActivity(), "请输入姓名", Toast.LENGTH_LONG).show();
			return valid;
		}
		valid &= emailInput.getText().length() > 0;
		if (!valid) {
			Toast.makeText(getActivity(), "请输入邮箱", Toast.LENGTH_LONG).show();
			return valid;
		}
		p = Pattern
				.compile("^([a-z0-9A-Z]*[_|\\.]?[a-z0-9A-Z]+)+@([a-z0-9A-Z]*[_]?[a-z0-9A-Z]+)+[\\.][a-zA-Z]{2,3}([\\.][a-zA-Z]{2})?$");
		matcher = p.matcher(emailInput.getText());
		if (!matcher.matches()) {
			Toast.makeText(getActivity(), "请输入合法邮箱", Toast.LENGTH_LONG).show();
			return false;
		}
		valid &= passwordInput.getText().length() > 0;
		if (!valid) {
			Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_LONG).show();
			return valid;
		}
		valid &= confirmPasswordInput.getText().length() > 0;
		if (!valid) {
			Toast.makeText(getActivity(), "请输入确认密码", Toast.LENGTH_LONG).show();
			return valid;
		}
		valid &= confirmPasswordInput.getText().toString()
				.equals(passwordInput.getText().toString());
		if (!valid) {
			Toast.makeText(getActivity(), "两次密码输入不一致", Toast.LENGTH_LONG)
					.show();
			return valid;
		}
		if (recommenderInput.getText().length() <= 0) {
			Toast.makeText(getActivity(), "请输入推荐人", Toast.LENGTH_LONG).show();
			return false;
		}
		valid &= checked;
		if (!valid) {
			Toast.makeText(getActivity(), "您需要同意并接受服务条款", Toast.LENGTH_LONG)
					.show();
			return valid;
		}
		return valid;
	}

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

	/**
	 * email:邮箱 pwd:密码 region:地区 sign:签名字符串
	 */
	private void performRegister() {
		RegRequest request = new RegRequest();
		request.setEmail(emailInput.getText().toString());
		request.setMobileNo(accountInput.getText().toString());
		request.setPwd(passwordInput.getText().toString());
		request.setRegion(regions.get(selectedRegion).id);
		request.setRecommendId(recommenderInput.getText().toString());
//		if (recommenderInput.getText().toString().trim().length() > 0)
			request.setRecommendId(recommenderInput.getText().toString());
		this.showProgressDialog("注册中", false);
		request.setHandler(new ResponseHandler() {

			@Override
			public void handleResponse(BaseRequest request, int statusCode,
					String errorMsg, String response) {
				ViewUtils.runInMainThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						RegisterFragment.this.dismissProgressDialog();

					}
				});

				if (statusCode == 200) {
					boolean success = false;
					String memberId = null;
					String msg = null;
					try {
						JSONObject object = new JSONObject(response);
						success = object.optBoolean("success", false);
						memberId = object.optString("memberId", null);
						msg = object.optString("msg", null);

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (success && memberId != null) {
						DCUser.sharedUser().setName(
								nameInput.getText().toString());
						DCUser.sharedUser().setUserId(memberId);
						DCUser.sharedUser().setPassword(
								passwordInput.getText().toString());
						DCUser.sharedUser().save();
						RegisterFragment.this.getActivity().finish();

					} else {
						final String errmsg = msg;
						ViewUtils.runInMainThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Toast.makeText(getActivity(),
										errmsg != null ? errmsg : "注册失败",
										Toast.LENGTH_LONG).show();
							}
						});
					}

				} else {
					ViewUtils.runInMainThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getActivity(), "连接服务器失败",
									Toast.LENGTH_LONG).show();
						}
					});
				}

			}
		}).start();
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "用户注册";
	}
}
